package com.axend.sofa.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_room.entity.SofaLogEntity
import com.axend.lib_room.manager.LogManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LogViewModel : BaseViewModel() {

    /*日志数据*/
    private var _logList: MutableLiveData<List<SofaLogEntity>> = MutableLiveData()
    val logList: LiveData<List<SofaLogEntity>> get() = _logList


    /*页码数量*/
    private var _pageSize: MutableLiveData<Int> = MutableLiveData(20)
    val pageSize: LiveData<Int> get() = _pageSize

    /*页码*/
    private var _pageIndex: MutableLiveData<Int> = MutableLiveData(1)
    val pageIndex: LiveData<Int> get() = _pageIndex


    fun getLogList(pageIndex: Int, pageSize: Int) {
        launchOnUI {
            val result = withContext(Dispatchers.IO) {
                LogManager.getLogListByPage(pageSize, pageIndex)
            }
            setLogList(result as MutableList<SofaLogEntity> , pageIndex==0)
        }
    }


    private fun setLogList(list: List<SofaLogEntity>, isRefresh: Boolean = false) {
        launchOnUI {
            if (isRefresh){
                _logList.value = listOf()
            }
            var dataList = _logList.value.orEmpty().toMutableList()
            dataList.addAll(list)
            _logList.postValue(dataList)
        }
    }


    fun deleteAllLog() {
        launchOnUI {
            withContext(Dispatchers.IO) {
                LogManager.deleteAll {
                    _logList.postValue(emptyList())
                }
            }
        }
    }


    fun setPageSize(size: Int) {
        launchOnUI {
            _pageSize.postValue(size)
        }
    }


    fun setPageIndex(index: Int) {
        launchOnUI {
            _pageIndex.postValue(index)
        }
    }
}